import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';
import common from '../../lib/common/common.js';

const storagePath = './temp/bilibili';
const shouldCoinFilePath = './temp/bilibili/should_coin.txt';

export class ExamplePlugin extends plugin {
    constructor() {
        super({
            name: "b站功能",
            desc: "我爱啊逼",
            event: "message",
            priority: -Infinity,
            rule: [
                {
                    reg: /^我的(b站|哔站|逼站|币站)$/,
                    fnc: "bili"
                },
                {
                  reg: /^(b站|哔站|逼站|币站)签到$/,
                  fnc: "signBilibili"
              },
                {
                    reg: '^(b站|哔站|逼站|币站|B站)?(开启|关闭)(b站|哔站|逼站|币站|B站)?(自动)?投币(功能)?$',
                    fnc: "controlCoinSwitch"
                }
            ]
        });
        this.task = {
            cron: '20 1 0 1/1 * ?',
            name: 'b站自动更新签到',
            fnc: () => this.autosign()
        };
        this.storagePath = storagePath;

        if (!fs.existsSync(path.dirname(shouldCoinFilePath))) {
            fs.mkdirSync(path.dirname(shouldCoinFilePath), { recursive: true });
        }

        try {
            if (!fs.existsSync(shouldCoinFilePath)) {
                fs.writeFileSync(shouldCoinFilePath, '', 'utf8'); 
                logger.info(`创建新的投币状态文件: ${shouldCoinFilePath}`);
            }
        } catch (err) {
            logger.error("无法创建是否投币文件:", err);
        }
    }

    async controlCoinSwitch(e) {
        const action = e.msg.includes('开启') ? '开启' :
                       e.msg.includes('关闭') ? '关闭' : '';

        if (!action) {
            e.reply('指令格式不对，请使用 "开启自动投币" 或 "关闭自动投币" 格式', true);
            return;
        }

        let fileContent = '';
        try {
            // 尝试读取现有文件内容
            fileContent = fs.readFileSync(shouldCoinFilePath, 'utf8');
        } catch (err) {
            // 如果读取文件出现错误，则记录警告信息
            logger.warn("无法读取是否投币文件:", err);
        }

        // 准备更新文件内容
        const userStatusLine = `${e.user_id}:${action === '开启' ? 'true' : 'false'}`;
        const lines = fileContent.split('\n').filter(line => !line.startsWith(`${e.user_id}:`));
        lines.push(userStatusLine);

        // 写入更新后的内容到文件
        try {
            fs.writeFileSync(shouldCoinFilePath, lines.join('\n'), 'utf8');
            logger.info(`用户 ${e.user_id} 的投币状态已设置为: ${action}`);
            e.reply(`投币功能已${action}`, true);
        } catch (err) {
            logger.error("无法写入是否投币文件:", err);
            e.reply("设置投币状态失败", true);
        }
    }


    async  autosign() {
        const cookieFile = path.join(this.storagePath, 'user_cookies.json');
        let cookies = {};
        try {
            cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
        } catch (err) {
            logger.error("无法读取cookie文件:", err);
            return;
        }
    
        // 遍历所有用户的cookies
        for (const [userId, userCookies] of Object.entries(cookies)) {
            if (!userCookies || !userCookies.SESSDATA) continue;
    
            const sessdata = userCookies.SESSDATA;
            const csrf = userCookies.csrf;
            const DedeUserID = userCookies.DedeUserID;
            const DedeUserID__ckMd5 = userCookies.DedeUserID__ckMd5;
            const sid = userCookies.sid;
            const access_token = userCookies.access_token;
    
            const baseHeaders = {
                'referer': 'https://www.bilibili.com',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
                'Cookie': `SESSDATA=${sessdata};`
            };
    
            // 检查是否投币文件并获取用户投币状态
            let shouldCoin = true; // 默认值为true，即默认要投币
                const fileContent = fs.readFileSync(shouldCoinFilePath, 'utf8');
                const userCoinStatus = fileContent.split('\n').find(line => line.startsWith(`${userId}:`));
                if (userCoinStatus && userCoinStatus.split(':')[1].trim() === 'false') {
                    shouldCoin = false; // 如果是false，则设置为不投币
                }
    
            try {
                // 获取指纹信息
                const fingerSpiUrl = 'https://api.bilibili.com/x/frontend/finger/spi';
                const fingerSpiResponse = await fetch(fingerSpiUrl, { headers: baseHeaders });
                if (!fingerSpiResponse.ok) throw new Error("获取 buvid3 请求失败");
                const fingerSpiData = await fingerSpiResponse.json();
                if (fingerSpiData.code !== 0) throw new Error(`获取 buvid3 失败: ${fingerSpiData.message}`);
    
                const buvid3 = fingerSpiData.data.b_3;
    
                // 更新 headers 以包含 buvid3
                const updatedBaseHeaders = {
                    ...baseHeaders,
                    'Cookie': `access_token=${access_token}; bili_jct=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}; SESSDATA=${sessdata}; buvid3=${buvid3}`
                };
    
                // 检查用户等级和已投币情况
                const myInfoUrl = 'https://api.bilibili.com/x/space/myinfo';
                const myInfoResponse = await fetch(myInfoUrl, { headers: updatedBaseHeaders });
                if (!myInfoResponse.ok) throw new Error("获取用户信息请求失败");
                const myInfoData = await myInfoResponse.json();
                if (myInfoData.code !== 0) throw new Error(`获取用户信息失败: ${myInfoData.message}`);
                const urlReward = 'https://api.bilibili.com/x/member/web/exp/reward';
                const urlRewardResponse = await fetch(urlReward, { headers: updatedBaseHeaders });
                const Reward = await urlRewardResponse.json();
                const coin = Reward.data.coins;
                const userLevel = myInfoData.data.level;
                logger.mark(`用户等级为：${userLevel}`);
                logger.mark(`今日已投币：${coin}`);
    
                // 获取推荐视频列表
                const rcmdUrl = 'https://api.bilibili.com/x/web-interface/wbi/index/top/feed/rcmd';
                const rcmdResponse = await fetch(rcmdUrl, { headers: updatedBaseHeaders });
                if (!rcmdResponse.ok) throw new Error("获取推荐视频列表请求失败");
                const rcmdData = await rcmdResponse.json();
                if (rcmdData.code !== 0 || rcmdData.data.item.length < 3) throw new Error("获取推荐视频列表失败或列表不足三个视频");
    
                // 随机选取3个不同的item
                let items = [...rcmdData.data.item];
                items = shuffle(items).slice(0, 3); // 使用shuffle函数来随机排序并选择前三个
    
                // 构建日志消息
                let videoLogs = '';
                for (let i = 0; i < items.length; i++) {
                    await common.sleep(5000); 
                    const item = items[i];
                    const bvid = item.bvid;
                    const aid = item.id;
                    const cid = item.cid;
                    const coinMultiply = i < 2 ? 2 : 1; // 前两个视频投2个币，最后一个视频投1个币
    
                    // 模拟观看视频操作
                    const watchUrl = 'https://api.bilibili.com/x/v2/history/report';
                    const watchFormData = new URLSearchParams({
                        aid: String(aid),
                        cid: String(cid),
                        progress: '90',
                        csrf
                    });
    
                    const watchHeaders = {
                        ...updatedBaseHeaders,
                        'Content-Type': 'application/x-www-form-urlencoded'
                    };
    
                    const watchResponse = await fetch(watchUrl, { method: 'POST', headers: watchHeaders, body: watchFormData });
                    const watchResult = await watchResponse.json();
                    const watchSuccess = watchResult.code === 0 ? '成功(首次5经验,首次登录5经验)' : `失败: ${watchResult.message}`;
    
                    // 投币或点赞操作
                    let coinAddSuccess;
                    if (shouldCoin && userLevel < 6 && coin < '50') {
                        // 执行投币操作
                        const coinAddUrl = 'https://app.bilibili.com/x/v2/view/coin/add';
                        const formData = new URLSearchParams({
                            access_key: access_token,
                            aid,
                            multiply: String(coinMultiply),
                            select_like: '1'
                        });
    
                        const likeShareHeaders = {
                            ...updatedBaseHeaders,
                            'Content-Type': 'application/x-www-form-urlencoded'
                        };
    
                        const coinAddResponse = await fetch(coinAddUrl, { method: 'POST', headers: likeShareHeaders, body: formData });
                        const coinAddResult = await coinAddResponse.json();
                        coinAddSuccess = coinAddResult.code === 0 ? `成功(${String(coinMultiply)}0经验)` : `失败: ${coinAddResult.message}`;
                        await common.sleep(10000);
                    } else {
                        // 不投币，执行点赞视频操作
                        const likeUrl = 'https://api.bilibili.com/x/web-interface/archive/like';
                        const likeFormData = new URLSearchParams({
                            bvid,
                            like: '1',
                            csrf
                        });
    
                        const likeHeaders = {
                            ...updatedBaseHeaders,
                            'Content-Type': 'application/x-www-form-urlencoded'
                        };
    
                        const likeResponse = await fetch(likeUrl, { method: 'POST', headers: likeHeaders, body: likeFormData });
                        const likeResult = await likeResponse.json();
                        coinAddSuccess = likeResult.code === 0 ? '仅点赞视频不投币成功(5经验)' : `仅点赞视频不投币失败: ${likeResult.message}`;
                    }
    
                    // 添加到日志消息
                    videoLogs += `
视频${i + 1}:
--------------------
视频地址：https://www.bilibili.com/video/${bvid}
观看结果：${watchSuccess}
投币结果：${coinAddSuccess}`;
                }
                await common.sleep(1000); 
                // 执行分享操作（假设分享最后一个视频）
                const shareUrl = 'https://api.bilibili.com/x/web-interface/share/add';
                const shareFormData = new URLSearchParams({
                    csrf,
                    bvid: items[items.length - 1].bvid
                });
                const shareResponse = await fetch(shareUrl, { method: 'POST', headers: updatedBaseHeaders, body: shareFormData });
                const shareResult = await shareResponse.json();
                const shareSuccess = shareResult.code === 0 ? '成功(5经验)' : `失败: ${shareResult.message}`;
    
                // 卡券兑换操作
                const privilegeReceiveUrl = 'https://api.bilibili.com/x/vip/privilege/receive';
                const privilegeResults = [];
                const privilegeTypes = {
                    1: 'B币券',
                    2: '会员购优惠券',
                    3: '漫画福利券',
                    4: '会员购包邮券',
                    5: '漫画商城优惠券',
                    6: '装扮体验卡',
                    7: '课堂优惠券'
                };
    
                for (let type = 1; type <= 7; type++) {
                    await common.sleep(3000);
                    const privilegeHeaders = {
                        ...updatedBaseHeaders,
                        'Content-Type': 'application/x-www-form-urlencoded'
                    };
    
                    const privilegeFormData = new URLSearchParams({
                        type: String(type),
                        csrf
                    });
    
                    const privilegeResponse = await fetch(privilegeReceiveUrl, {
                        method: 'POST',
                        headers: privilegeHeaders,
                        body: privilegeFormData.toString()
                    });
                    const privilegeResult = await privilegeResponse.json();
                    privilegeResults.push(`${privilegeTypes[type]}: ${privilegeResult.message}`);
                }
                await common.sleep(1000); 
                // 大会员经验签到
                const vipExpSignUrl = 'https://api.bilibili.com/x/vip/experience/add';
                const vipExpSignHeaders = {
                    ...updatedBaseHeaders,
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    
                const vipExpSignFormData = new URLSearchParams({ csrf });
    
                const vipExpSignResponse = await fetch(vipExpSignUrl, {
                    method: 'POST',
                    headers: vipExpSignHeaders,
                    body: vipExpSignFormData.toString()
                });
                const vipExpSignResult = await vipExpSignResponse.json();
                const vipExpSignMsg = vipExpSignResult.code === 0 ? '大会员经验签到成功(10经验)' : `${vipExpSignResult.message}`;
                await common.sleep(1000); 
                // 漫画签到
                const mangaClockInUrl = 'https://manga.bilibili.com/twirp/activity.v1.Activity/ClockIn';
                const mangaClockInHeaders = {
                    ...updatedBaseHeaders,
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    
                const mangaClockInResponse = await fetch(mangaClockInUrl, {
                    method: 'POST',
                    headers: mangaClockInHeaders,
                    body: new URLSearchParams({ platform: 'android' }).toString()
                });
                const mangaClockInResult = await mangaClockInResponse.json();
                const mangaClockInMsg = mangaClockInResult.code === 0 ? '漫画签到成功' : `${mangaClockInResult.msg}`;
                
                // 构建日志消息并记录
                const logmsg = `[哔站自动签到推送]\n【我的哔站】查看最近一周经验详情\n本次签到结果：
--------------------
大会员经验签到：${vipExpSignMsg}
漫画签到：${mangaClockInMsg}
--------------------
${videoLogs}
--------------------
分享结果：${shareSuccess}
--------------------
卡券兑换结果：
${privilegeResults.join('\n')}
结果0代表成功
--------------------`;
    
if(await redis.get(`${userId}`)){
        const groupid = await redis.get(`${userId}`)

if (!isNaN(groupid) && groupid !== undefined && groupid.trim() !== '') {
    // 如果是数字，执行某个方法
    Bot.pickGroup(groupid).sendMsg([segment.at(userId),logmsg])
} else {
    // 如果不是数字，执行另一个方法
    Bot.pickFriend(userId).sendMsg(logmsg)
    }
}
logger.info(logmsg);
            } catch (error) {
                logger.error(`发生错误: ${error.message}`);
            }
        }
    }
    
    async  signBilibili(e) {
        const cookieFile = path.join(this.storagePath, 'user_cookies.json');

        let cookies = {};
        try {
            cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
        } catch (err) {
            logger.error("无法读取cookie文件:", err);
            e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
            return;
        }
    
        // 检查是否投币文件并获取用户投币状态
        let shouldCoin = true; // 默认值为true，即默认要投币
        try {
            const fileContent = fs.readFileSync(shouldCoinFilePath, 'utf8');
            const userCoinStatus = fileContent.split('\n').find(line => line.startsWith(`${e.user_id}:`));
            if (userCoinStatus && userCoinStatus.split(':')[1].trim() === 'false') {
                shouldCoin = false; // 如果是false，则设置为不投币
            }
        } catch (err) {
            logger.warn("无法读取是否投币文件:", err);
        }
    
        const userCookies = cookies[e.user_id];
        if (!userCookies || !userCookies.SESSDATA) {
            e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
            return;
        }
    
        const sessdata = userCookies.SESSDATA;
        const csrf = userCookies.csrf;
        const DedeUserID = userCookies.DedeUserID;
        const DedeUserID__ckMd5 = userCookies.DedeUserID__ckMd5;
        const sid = userCookies.sid;
    
        const baseHeaders = {
            'referer': 'https://www.bilibili.com',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Cookie': `SESSDATA=${sessdata};`
        };
    
        try {
            // 获取指纹信息
            const fingerSpiUrl = 'https://api.bilibili.com/x/frontend/finger/spi';
            const fingerSpiResponse = await fetch(fingerSpiUrl, { headers: baseHeaders });
            if (!fingerSpiResponse.ok) throw new Error("获取 buvid3 请求失败");
            const fingerSpiData = await fingerSpiResponse.json();
            if (fingerSpiData.code !== 0) throw new Error(`获取 buvid3 失败: ${fingerSpiData.message}`);
    
            const buvid3 = fingerSpiData.data.b_3;
    
            // 更新 headers 以包含 buvid3
            const updatedBaseHeaders = {
                ...baseHeaders,
                'Cookie': `access_token=${userCookies.access_token}; bili_jct=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}; ${baseHeaders.Cookie}; buvid3=${buvid3}`
            };
    
            // 获取推荐视频列表
            const rcmdUrl = 'https://api.bilibili.com/x/web-interface/wbi/index/top/feed/rcmd';
            const rcmdResponse = await fetch(rcmdUrl, { headers: updatedBaseHeaders });
            if (!rcmdResponse.ok) throw new Error("获取推荐视频列表请求失败");
            const rcmdData = await rcmdResponse.json();
            if (rcmdData.code !== 0 || rcmdData.data.item.length === 0) throw new Error("获取推荐视频列表失败或列表为空");
    
            // 随机选取一个 item
            const randomItem = rcmdData.data.item[Math.floor(Math.random() * rcmdData.data.item.length)];
            const bvid = randomItem.bvid;
            const aid = randomItem.id;
            const cid = randomItem.cid;
    
            // 模拟观看视频操作
            const watchUrl = 'https://api.bilibili.com/x/v2/history/report';
            const watchFormData = new URLSearchParams({
                aid: String(aid),
                cid: String(cid),
                progress: '90',
                csrf
            });
    
            const watchHeaders = {
                ...updatedBaseHeaders,
                'Content-Type': 'application/x-www-form-urlencoded'
            };
    
            const watchResponse = await fetch(watchUrl, { method: 'POST', headers: watchHeaders, body: watchFormData });
            const watchResult = await watchResponse.json();
            const watchSuccess = watchResult.code === 0 ? '成功' : `失败: ${watchResult.message}`;
    
            // 检查用户等级和投币次数
            const myInfoUrl = 'https://api.bilibili.com/x/space/myinfo';
            const myInfoResponse = await fetch(myInfoUrl, { headers: updatedBaseHeaders });
            if (!myInfoResponse.ok) throw new Error("获取用户信息请求失败");
            const myInfoData = await myInfoResponse.json();
            if (myInfoData.code !== 0) throw new Error(`获取用户信息失败: ${myInfoData.message}`);
            const urlReward = 'https://api.bilibili.com/x/member/web/exp/reward';
            const urlRewardResponse = await fetch(urlReward, { headers: updatedBaseHeaders });
            const Reward = await urlRewardResponse.json();
            const coin = Reward.data.coins
            const userLevel = myInfoData.data.level;
            logger.mark(`用户等级为：${userLevel}`);
            logger.mark(`今日已投币：${coin}`);
    
            // 投币或点赞操作
            let coinAddSuccess;
            if ((userLevel === 6 || coin === '50') && shouldCoin) {
                // 如果用户等级为6级或已投币50次，并且允许投币，则不执行投币操作
                coinAddSuccess = `不执行：您等级为${userLevel}或已投币${coin}`;
                logger.warn(coinAddSuccess);
            } else if (shouldCoin) {
                // 执行投币操作
                const coinAddUrl = 'https://app.bilibili.com/x/v2/view/coin/add';
                const formData = new URLSearchParams({
                    access_key: userCookies.access_token,
                    aid,
                    multiply: '2',
                    select_like: '1'
                });
    
                const likeShareHeaders = {
                    ...updatedBaseHeaders,
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    
                const coinAddResponse = await fetch(coinAddUrl, { method: 'POST', headers: likeShareHeaders, body: formData });
                const coinAddResult = await coinAddResponse.json();
                coinAddSuccess = coinAddResult.code === 0 ? '成功' : `失败: ${coinAddResult.message}`;
                await common.sleep(1000);
            } else {
                // 不投币，执行点赞视频操作
                const likeUrl = 'https://api.bilibili.com/x/web-interface/archive/like';
                const likeFormData = new URLSearchParams({
                    bvid,
                    like: '1',
                    csrf
                });
    
                const likeHeaders = {
                    ...updatedBaseHeaders,
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    
                const likeResponse = await fetch(likeUrl, { method: 'POST', headers: likeHeaders, body: likeFormData });
                const likeResult = await likeResponse.json();
                coinAddSuccess = likeResult.code === 0 ? '仅点赞视频不投币成功' : `仅点赞视频不投币失败: ${likeResult.message || likeResult.msg}`;
                await common.sleep(1000);
            }
    
            // 执行分享操作
            const shareUrl = 'https://api.bilibili.com/x/web-interface/share/add';
            const shareFormData = new URLSearchParams({
                csrf,
                bvid
            });
            const likeShareHeaders = {
                ...updatedBaseHeaders,
                'Content-Type': 'application/x-www-form-urlencoded'
            };
            const shareResponse = await fetch(shareUrl, { method: 'POST', headers: likeShareHeaders, body: shareFormData });
            const shareResult = await shareResponse.json();
            const shareSuccess = shareResult.code === 0 ? '成功' : `失败: ${shareResult.message}`;
    
            // 卡券兑换操作
            const privilegeReceiveUrl = 'https://api.bilibili.com/x/vip/privilege/receive';
            const privilegeResults = [];
            const privilegeTypes = {
                1: 'B币券',
                2: '会员购优惠券',
                3: '漫画福利券',
                4: '会员购包邮券',
                5: '漫画商城优惠券',
                6: '装扮体验卡',
                7: '课堂优惠券'
            };
    
            for (let type = 1; type <= 7; type++) {
                await common.sleep(1000);
                const privilegeHeaders = {
                    ...updatedBaseHeaders,
                    'Content-Type': 'application/x-www-form-urlencoded'
                };
    
                const privilegeFormData = new URLSearchParams({
                    type: String(type),
                    csrf
                });
    
                const privilegeResponse = await fetch(privilegeReceiveUrl, {
                    method: 'POST',
                    headers: privilegeHeaders,
                    body: privilegeFormData.toString()
                });
                const privilegeResult = await privilegeResponse.json();
                privilegeResults.push(`${privilegeTypes[type]}: ${privilegeResult.message}`);
            }
    
            // 大会员经验签到
            const vipExpSignUrl = 'https://api.bilibili.com/x/vip/experience/add';
            const vipExpSignHeaders = {
                ...updatedBaseHeaders,
                'Content-Type': 'application/x-www-form-urlencoded'
            };
    
            const vipExpSignFormData = new URLSearchParams({ csrf });
    
            const vipExpSignResponse = await fetch(vipExpSignUrl, {
                method: 'POST',
                headers: vipExpSignHeaders,
                body: vipExpSignFormData.toString()
            });
            const vipExpSignResult = await vipExpSignResponse.json();
            const vipExpSignMsg = vipExpSignResult.code === 0 ? '大会员经验签到成功' : `${vipExpSignResult.message}`;
    
            // 漫画签到
            const mangaClockInUrl = 'https://manga.bilibili.com/twirp/activity.v1.Activity/ClockIn';
            const mangaClockInHeaders = {
                ...updatedBaseHeaders,
                'Content-Type': 'application/x-www-form-urlencoded'
            };
    
            const mangaClockInResponse = await fetch(mangaClockInUrl, {
                method: 'POST',
                headers: mangaClockInHeaders,
                body: new URLSearchParams({ platform: 'android' }).toString()
            });
            const mangaClockInResult = await mangaClockInResponse.json();
            const mangaClockInMsg = mangaClockInResult.code === 0 ? '漫画签到成功' : `${mangaClockInResult.msg}`;
    
            // 构建回复消息并发送给用户
            const replymsg = `用户 ${e.user_id} 签到结果：
--------------------
大会员经验签到：${vipExpSignMsg}
漫画签到：${mangaClockInMsg}
--------------------
观看视频结果：${watchSuccess}
一键三连结果：${coinAddSuccess}
分享结果：${shareSuccess}
--------------------
卡券兑换结果：
${privilegeResults.join('\n')}
结果0代表成功
--------------------
视频地址：https://www.bilibili.com/video/${bvid}`;
            e.reply(replymsg, true);
    
        } catch (error) {
            logger.error(`发生错误: ${error.message}`);
            e.reply(`发生错误: ${error.message}`, true);
        }
    }
    async  bili(e) {
        const cookieFile = path.join(this.storagePath, 'user_cookies.json');
        let cookies = {};
        try {
            cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
        } catch (err) {
            console.error("无法读取cookie文件:", err);
            e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
            return;
        }
    
        const userCookies = cookies[e.user_id];
        if (!userCookies || !userCookies.SESSDATA) {
            e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
            return;
        }
        const sessdata = userCookies.SESSDATA;
        const csrf = userCookies.csrf;
        const DedeUserID = userCookies.DedeUserID;
        const DedeUserID__ckMd5 = userCookies.DedeUserID__ckMd5;
        const sid = userCookies.sid;
    
        const urlInfo = 'https://api.bilibili.com/x/space/myinfo';
        const urlReward = 'https://api.bilibili.com/x/member/web/exp/reward';
        const urlExpLog = 'https://api.bilibili.com/x/member/web/exp/log'; 
    
        const headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
            'Cookie': `SESSDATA=${sessdata}; access_token=${userCookies.access_token}; bili_jct=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}; `
        };
    
        try {
            const [responseInfo, responseReward, responseExpLog] = await Promise.all([
                fetch(urlInfo, {headers}),
                fetch(urlReward, {headers}),
                fetch(urlExpLog, {headers})
            ]);
    
            const [dataInfo, dataReward, dataExpLog] = await Promise.all([
                responseInfo.json(),
                responseReward.json(),
                responseExpLog.json()
            ]);
            if (dataInfo.code !== 0 || dataReward.code !== 0 || dataExpLog.code !== 0) {
                e.reply(`请求失败，错误码: ${dataInfo.code} ： ${dataReward.code} ： ${dataExpLog.code}`, true);
                return;
            }
    
            const user = dataInfo.data;
            const vipInfo = user.vip.type > 0 ? 
            `${user.vip.label.text}\n过期时间: ${new Date(user.vip.due_date).toISOString().replace('T', ' ').substring(0, 19)}` : 
            '无会员';
            const levelUpExp = user.level_exp.next_exp - user.level_exp.current_exp;
            const birthday = new Date(user.birthday * 1000);
            const formattedBirthday = `${birthday.getFullYear()}-${(birthday.getMonth() + 1).toString().padStart(2, '0')}-${birthday.getDate().toString().padStart(2, '0')}`;
    
            const rewardContent = `
---
### 每日任务完成情况
- **每日登录**：${dataReward.data.login ? '已完成 (奖励5经验)' : '未完成(可以获得5经验)'}
- **每日观看**：${dataReward.data.watch ? '已完成 (奖励5经验)' : '未完成(可以获得5经验)'}
- **每日投币**：已获得 ${dataReward.data.coins} 经验（上限为50）
- **每日分享**：${dataReward.data.share ? '已完成 (奖励5经验)' : '未完成(可以获得5经验)'}
- **绑定邮箱**：${dataReward.data.email ? '已完成 (首次完成奖励20经验)' : '未完成(首次完成奖励20经验)'}
- **绑定手机号**：${dataReward.data.tel ? '已完成 (首次完成奖励100经验)' : '未完成(首次完成奖励100经验)'}
- **设置密保问题**：${dataReward.data.safe_question ? '已完成 (首次完成奖励30经验)' : '未完成(首次完成奖励30经验)'}
- **实名认证**：${dataReward.data.identify_card ? '已完成 (首次完成奖励50经验)' : '未完成(首次完成奖励50经验)'}
    `;
    
            const expLogContent = dataExpLog.data.list.map(item => 
                `**${item.reason}**\n${item.time}\n获得${item.delta} 经验\n------------------`
            ).join('\n');
    
            const content = `
![图片 #210px #210px](${user.face})
---
>用户名：${user.name}
>用户uid：${user.mid}
>用户状态：${user.silence === 0 ? '正常' : '封禁'}
>性别：${user.sex}
>生日：${formattedBirthday}
---
---
>会员情况：${vipInfo}
---
---
当前等级：${user.level}
当前经验：${user.level_exp.current_exp}
升级所需经验：${levelUpExp}
升级所需天数: ${Math.ceil(levelUpExp / 75)}
硬币数：${user.coins}
粉丝数：${user.follower}
${rewardContent}
---
###最近的一周经验信息
\`\`\`json
${expLogContent.length > 0 ? expLogContent : "没有最近的经验记录"}
\`\`\`
`;
    
            const forwardMsgData = {
                group_id: e.group_id,
                user_id: e.user_id,
                message: [
                  {
                    type: 'node',
                    data: {
                      nickname: e.sender.nickname,
                      user_id: e.user_id,
                      content: {
                        type: 'node',
                        data: {
                          nickname: e.sender.nickname,
                          user_id: e.user_id,
                          content: [
                            {
                              type: 'markdown',
                              data: {
                                content: content
                               }
                            }
                          ]
                        }
                      },
                      news: [{ text: `${user.name}的哔站` }]
                    }
                  }
                ],
                news: [{ text: "查询成功！" },{ text: "ZY - YYDS" }]
              };
    
            await e.bot.sendApi('send_group_forward_msg', forwardMsgData);
    
        } catch (error) {
            console.error('发生错误:', error);
            e.reply('发生了未知错误，请稍后再试。', true);
        }
    }
}
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}